<template>
  <Layout>
    <section class="p-5 bg-white mb-5">
      <el-form
        ref="queryForm"
        label-width="120px"
        class="flex flex-wrap"
        :model="originQuery"
      >
        <el-form-item
          class="w-4/12"
          label="起运港"
          prop="portStart"
        />
        <el-form-item
          class="w-4/12"
          label="目的港"
          prop="portArrive"
        />
        <el-form-item
          class="w-4/12"
          label="创建公司"
          prop="corpId"
        >
          <el-select
            v-model="originQuery.corpId"
            clearable
            filterable
            remote
            reserve-keyword
            placeholder="请输入企业名称"
            :remote-method="queryCompanyInfo"
          >
            <el-option
              v-for="item in companyOpts"
              :key="item.corpId"
              :label="item.qdCompanyName"
              :value="item.corpId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="w-4/12"
          label="发布时间"
          prop="__dateRange$fromDate$toDate"
        >
          <el-date-picker
            v-model.trim="originQuery.__dateRange$fromDate$toDate"
            :picker-options="pickerOptions"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item
          class="w-4/12"
          label="创建时间"
          prop="__dateRange$fromDateCreate$toDateCreate"
        >
          <el-date-picker
            v-model.trim="
              originQuery.__dateRange$fromDateCreate$toDateCreate
            "
            :picker-options="pickerOptions"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="() => handleQuery({ num: 1 })"
          >
            查询
          </el-button>
          <el-button
            type="primary"
            :disabled="loading"
            @click="() => handleExport()"
          >
            导出
          </el-button>
          <el-button @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </section>
    <section>
      <el-table
        ref="table"
        :data="tableList"
        border
      >
        <el-table-column
          label="舱位编号"
          prop="id"
        />
        <el-table-column
          label="起运港"
          prop="portStart"
        />
        <el-table-column
          label="目的港"
          prop="portArrive"
        />
        <el-table-column
          label="中转港"
          prop="portTransit"
        />
        <el-table-column
          label="航线代码"
          prop="shippingLineCode"
        />
        <el-table-column
          label="航程"
          prop="sail"
        />
        <el-table-column label="ETD">
          <template #default="{ row }">
            <span>
              {{ returnShortDate(row.etd) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="箱型箱量">
          <template #default="{ row }">
            {{ row.boxsStr == '*' ? '' : row.boxsStr }}
          </template>
        </el-table-column>
        <el-table-column
          label="船公司"
          prop="shippingCompany"
        />
        <!-- <el-table-column label="卖价/箱" prop="shippingCompany">
                    <template #default="{ row }">
                        {{ calcSaleStr(row) }}
                    </template>
                </el-table-column>
                <el-table-column label="成本/箱" prop="shippingCompany">
                    <template #default="{ row }">
                        {{ calcCostStr(row) }}
                    </template>
                </el-table-column> -->
        <el-table-column
          label="创建公司"
          prop="pushCompanyName"
        />
        <el-table-column
          label="创建人"
          prop="createBy"
        />
        <el-table-column
          label="创建人手机号"
          prop="pushPhone"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
        />
        <el-table-column
          label="是否发布"
          prop="pushShippingMarketFlag"
        >
          <template #default="{ row }">
            {{ row.pushShippingMarketFlag ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column
          label="发布次数"
          prop="publishCount"
        >
          <template #default="{ row }">
            <div
              class="underline"
              @click="handleGoDetail(row)"
            >
              {{
                row.pushShippingMarketFlag
                  ? row.publishCount
                  : '-'
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="最新发布时间"
          prop="pushTime"
        >
          <template #default="{ row }">
            {{ row.pushShippingMarketFlag ? row.pushTime : '-' }}
          </template>
        </el-table-column>
        <el-table-column
          label="触达用户人数"
          prop="subscribePerson"
        >
          <template #default="{ row }">
            {{
              row.pushShippingMarketFlag
                ? row.subscribePerson
                : '-'
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="触达用户人次"
          prop="subscribeNum"
        >
          <template #default="{ row }">
            {{
              row.pushShippingMarketFlag ? row.subscribeNum : '-'
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="发起沟通人数"
          prop="contactPerson"
        >
          <template #default="{ row }">
            {{
              row.pushShippingMarketFlag ? row.contactPerson : '-'
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="发起沟通人次"
          prop="contactNum"
        >
          <template #default="{ row }">
            {{
              row.pushShippingMarketFlag ? row.contactNum : '-'
            }}
          </template>
        </el-table-column>
      </el-table>
      <div class="text-center py-4">
        <el-pagination
          v-model:current-page="query.num"
          background
          :total="total"
          :page-size="query.size"
          @current-change="handlePageChange"
        />
      </div>
    </section>
  </Layout>
</template>

<script>
import Layout from '@/layout/index.vue'
import { queryCabinList, cabinExport, getReleaseCompany } from '@/api/cabin'
import dayjs from 'dayjs'
import { getTreeNode } from '@/api/harbor'
export default {
    components: {
        Layout
    },
    data() {
        return {
            query: {
                num: 1,
                size: 10
            },
            originQuery: {},
            tableList: [],
            harborList: [],
            companyList: [],
            companyOpts: [],
            companyOptsOrigin: [],
            total: 0,
            loading: false,
            pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                    this.selectDate = minDate.getTime()
                    if (maxDate) {
                        this.selectDate = ''
                    }
                },
                disabledDate: (time) => {
                    let nowTime = Date.now()
                    const getDisable = () => {
                        if (this.selectDate !== '') {
                            const one = 183 * 24 * 3600 * 1000
                            const minTime = this.selectDate - one
                            const maxTime = this.selectDate + one
                            return (
                                time.getTime() < minTime ||
                                time.getTime() > maxTime
                            )
                        }
                    }
                    return time.getTime() > nowTime || getDisable()
                }
            }
        }
    },
    created() {
        this.init()
        // this.queryCompanyInfo()
        this.getShownCompanyInfo()
    },
    // watch: {
    // 'originQuery.__dateRange$fromDateCreate$toDateCreate': {
    //     handler(n) {
    //         if (n) return
    //         let nowTime = Date.now()
    //         this.originQuery.__dateRange$fromDateCreate$toDateCreate = [
    //             dayjs(nowTime)
    //                 .subtract(183, 'day')
    //                 .format('YYYY-MM-DD HH:mm:ss'),
    //             dayjs(nowTime).format('YYYY-MM-DD HH:mm:ss'),
    //         ]
    //     },
    //     immediate: true,
    // },
    // 'originQuery.__dateRange$fromDate$toDate': {
    //     handler(n) {
    //         if (n) return
    //         let nowTime = Date.now()
    //         this.originQuery.__dateRange$fromDate$toDate = [
    //             dayjs(nowTime)
    //                 .subtract(183, 'day')
    //                 .format('YYYY-MM-DD HH:mm:ss'),
    //             dayjs(nowTime).format('YYYY-MM-DD HH:mm:ss'),
    //         ]
    //     },
    //     immediate: true,
    // },
    // },
    methods: {
        async handleGoDetail(row) {
            await this.$store.dispatch('cabin/setCabinId', row.id)
            this.$router.push('/cabin-detail')
        },
        calcSaleStr(val) {
            if (!val?.boxs) return
            const arr = []
            val.boxs.forEach((i) => {
                arr.push(`$${i.sale}/${i.boxType}`)
            })
            return arr.join(',')
        },
        calcCostStr(val) {
            if (!val?.boxs) return
            const arr = []
            val.boxs.forEach((i) => {
                arr.push(`$${i.cost}/${i.boxType}`)
            })
            return arr.join(',')
        },
        async handleExport() {
            if (
                !this.query.__dateRange$fromDateCreate$toDateCreate &&
                !this.query.__dateRange$fromDate$toDate
            )
                return this.$message.warning('导出必须选择一段时间')
            const q = {
                ...this.query
            }
            if (q.portArrive) {
                q.portArrive = q.portArriveId
            }
            if (q.portStart) {
                q.portStart = q.portStartId
            }
            try {
                this.loading = true
                let res = await cabinExport(q)
                const url = window.URL.createObjectURL(
                    new Blob([res], {
                        type:
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    })
                )
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute(
                    'download',
                    `舱位列表_${dayjs().format('YYYY-MM-DD_HH_mm_ss')}.xlsx`
                )
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            } catch (e) {
                console.log(e)
            } finally {
                this.loading = false
            }
        },
        handleAfterSelect(type, node) {
            if (type == 1) {
                if (!node) {
                    this.originQuery.portStart = ''
                    this.originQuery.portStartId = ''
                    this.originQuery.portStartLevel = ''
                }
                delete this.originQuery.metaStart
            }
            if (type == 2) {
                if (!node) {
                    this.originQuery.portArrive = ''
                    this.originQuery.portArriveId = ''
                    this.originQuery.portArriveLevel = ''
                }
                delete this.originQuery.metaArrive
            }
        },
        async getShownCompanyInfo() {
            let res = await getReleaseCompany({ isPublished: false })
            this.companyOptsOrigin = res.data
            this.companyOpts = res.data.slice(0, 100)
        },
        async queryCompanyInfo(val) {
            this.companyOpts = this.companyOptsOrigin
                .filter(
                    (i) =>
                        i.qdCompanyName.includes(val) || i.corpId.includes(val)
                )
                .slice(0, 100)
        },
        returnShortDate(val) {
            return val ? dayjs(val).format('YYYY-MM-DD') : val
        },
        async init() {
            this.handleQuery()
        },
        initData() {
            this.getHarborData()
        },
        handlePageChange() {
            this.searchFunc()
        },
        async getHarborData() {
            let res = await getTreeNode(0)
            this.harborList = res.data
        },
        async handleQuery() {
            this.query = { ...this.query, ...this.originQuery }
            this.query.num = 1
            this.searchFunc()
        },
        async searchFunc() {
            const p = {
                ...this.query
            }
            if (this.query.portStart) {
                p.portStart = this.query.portStartId
            }
            if (this.query.portArrive) {
                p.portArrive = this.query.portArriveId
            }
            let res = await queryCabinList(p)
            this.total = res.data.total
            this.tableList = res.data.records
        },
        handleReset() {
            this.query = {
                num: 1,
                size: 10
            }
            this.originQuery = {}
            this.handleQuery()
        }
    }
}
</script>
<style scoped>
.gray {
    color: gray;
}
.underline {
    cursor: pointer;
    color: #006aff;
}
</style>
